package handlers

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
	"video-linker/cache"
	"video-linker/models"
	"video-linker/pkg"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不能为空",
		})
		return
	}
	redis_key := "user_login_" + username
	errCount, _ := cache.Rdb.Get(cache.Ctx, redis_key).Int()
	if errCount >= 3 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误三次，禁止登录",
		})
		return
	}

	var user models.User
	err := models.DB.Where("username=?", username).First(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户名不存在",
		})
		return
	}
	if pkg.Md5Str(password) != user.Password {
		cache.Rdb.Incr(cache.Ctx, redis_key)
		if errCount == 2 {
			c.JSON(200, gin.H{
				"code": 500,
				"msg":  "密码错误三次，封禁2小时",
			})
			return
		}
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误",
		})
		return
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登录成功",
	})
	return
}

func Upload(c *gin.Context) {
	file, err := c.FormFile("img")
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "图片获取失败",
		})
		return
	}

	path := "static/img/" + file.Filename
	err = c.SaveUploadedFile(file, path)
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "上传失败",
		})
		return
	} else {
		url := "http://" + c.Request.Host + "/" + path
		c.JSON(200, gin.H{
			"code": 200,
			"msg":  "上传成功",
			"data": url,
		})
		return
	}
}

func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "5"))
	offset := (page - 1) * size
	var article []models.Article
	redis_key := "article_list_"
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Offset(offset).Limit(size).Find(&article)
		jsonData, _ := json.Marshal(article)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &article)
	}
	var total int64
	models.DB.Model(&models.Article{}).Count(&total)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "查询成功",
		"data":  article,
		"total": total,
	})
	return
}

func Detail(c *gin.Context) {
	id := c.Query("id")
	var article models.Article
	redis_key := "article_detail_" + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Where("id=?", id).First(&article)
		jsonData, _ := json.Marshal(article)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour)
	} else {
		json.Unmarshal([]byte(cacheData), &article)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": article,
	})
	return
}

func Like(c *gin.Context) {
	userId, _ := strconv.Atoi(c.Query("user_id"))
	articleId, _ := strconv.Atoi(c.Query("article_id"))
	var like models.Like
	err := models.DB.Where("user_id=? and article_id=?", userId, articleId).First(&like).Error
	if err == nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "不能重复点赞",
		})
		return
	}
	tx := models.DB.Begin()
	like = models.Like{
		UserId:    userId,
		ArticleId: userId,
	}
	err = tx.Create(&like).Error
	if err != nil {
		tx.Rollback()
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "点赞失败",
		})
		return
	}
	var article models.Article
	err = tx.Where("id=?", articleId).First(&article).Error
	if err != nil {
		tx.Rollback()
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "不存在",
		})
		return
	}
	article.LikeCount++
	err = tx.Save(&article).Error
	if err != nil {
		tx.Rollback()
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "点赞添加失败",
		})
		return
	}
	tx.Commit()

	c.JSON(200, gin.H{
		"code": 500,
		"msg":  "点赞成功",
	})
	return
}
